#!/usr/bin/env python
# -*- coding: utf-8 -*-

from gdata import service
import gdata, atom, urllib2
import eParser

class blog:
  def __init__(self, user, passwd):
    self.blogger_service = service.GDataService(user, passwd)
    self.blogger_service.source = 'eBoutique'
    self.blogger_service.service = 'blogger'
    self.blogger_service.account_type = 'GOOGLE'
    self.blogger_service.server = 'www.blogger.com'
    self.blogger_service.ProgrammaticLogin()

  def ListBlogs(self):
    query = service.Query()
    query.feed = '/feeds/default/blogs'
    feed = self.blogger_service.Get(query.ToUri())
    return feed.entry

  def CreatePost(self, blog_id, title, content):
    entry = gdata.GDataEntry()
    entry.title = atom.Title('xhtml', title)
    entry.content = atom.Content(content_type='html', text=content)
    return self.blogger_service.Post(entry, '/feeds/%s/posts/default' % blog_id)
  
  def ListPosts(self, blog_id):
    feed = self.blogger_service.GetFeed('/feeds/' + blog_id + '/posts/default')
    return feed.entry
    
  def CreatePage(self, blog_id, title, content):
    entry = gdata.GDataEntry()
    entry.title = atom.Title('xhtml', title)
    entry.content = atom.Content(content_type='html', text=content)
    return self.blogger_service.Post(entry, '/feeds/%s/pages/default' % blog_id)
  
  def ListPages(self, blog_id):
    feed = self.blogger_service.GetFeed('/feeds/' + blog_id + '/pages/default')
    return feed.entry
  
  def UpdateEntry(self, entry, update_type, new_text):
    if update_type == "title":
      entry.title = atom.Title('xhtml', new_text)
    elif update_type == "content":
      entry.content = atom.Content(content_type='html', text=new_text)
    return self.blogger_service.Put(entry, entry.GetEditLink().href)
    
  def getPostURL(self, blog_id, title):
    ua = "Mozilla/4.5b1 [en] (X11; I; Linux 2.0.35 i586)"
    h = {"User-Agent": ua}
    r = urllib2.Request("http://www.blogger.com/feeds/" + blog_id + "/posts/default", headers=h)
    html = urllib2.urlopen(r).read()
    uParser = eParser.parseURL(title)
    uParser.feed(html)
    return uParser.close()
    
                    
